package com.hyk.controller;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.collect.Maps;
import com.hyk.dto.ApiResult;
import com.hyk.entity.User;
import com.hyk.entity.request.UserLoginRequest;
import com.hyk.enums.ApiEnum;
import com.hyk.exception.GlobalException;
import com.hyk.service.IUserService;

import com.hyk.utils.*;
import io.swagger.annotations.Api;
import lombok.SneakyThrows;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hyk
 * @since 2021-03-10
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户登录")
@CrossOrigin
public class UserController {

    @Resource
    private IUserService userService;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @PostMapping("/upload")
    public ApiResult upload(@RequestBody MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        String newName = uuid + originalFilename;
        String filename = QiniuUtil.byteUpLoad(file.getBytes(),newName);
        return R.ok(filename);
    }

    @PostMapping("/add")
    public ApiResult add(@RequestBody User user){

        //user.setPassword(MD5Utils.encode(user.getPassword()));
        //密码加密
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));

        user.setUpdateTime(new Date());
        user.setCreateTime(new Date());
        userService.save(user);
        return R.ok();
    }

    @PostMapping("/update")
    public ApiResult update(@RequestBody User user){
       if (StringUtils.isNotBlank(user.getUsername())){
            user.setPassword(MD5Utils.encode(user.getPassword()));
       }
       userService.updateById(user);
       return R.ok();
    }

    @PostMapping("/delete")
    public ApiResult delete(@RequestBody User user){
        userService.removeById(user.getId());
        return R.ok();
    }

    @RequestMapping(value = "/verificationCode",method = RequestMethod.POST)
    public ApiResult verificationCode() throws IOException {
        //用户保存生成的图片 【 输出流】
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        //生成验证码图片
        ImageVerificationCode.output(ImageVerificationCode.getImage(),outputStream);
        //获取验证码图片中的信息
        String text = ImageVerificationCode.getText();

        //生成随机数的uuid 来u作为验证码的唯一标示
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //把验证码信息保存到redis缓存中并设置60秒的过期时间
        redisTemplate.opsForValue().set(uuid,text,60, TimeUnit.SECONDS);
        //将图片转化为base64的格式
        byte[] bytes = outputStream.toByteArray();
        String encoder = Base64.getEncoder().encodeToString(bytes);
        encoder = "data:image/png;base64," + encoder;
        //组装数据返回
        HashMap<Object, Object> objectObjectHashMap = Maps.newHashMap();
        objectObjectHashMap.put("encoder", encoder);
        objectObjectHashMap.put("key", uuid);
        return R.ok(objectObjectHashMap);
    }

    @PostMapping("/login")
    public ApiResult login(@RequestBody UserLoginRequest request,
                           HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse) throws Exception{

//        System.out.println("账号："+request.getUsername()+"  密码："+request.getPassword());
//
//        request.setUsername("root");
//        request.setPassword("123456");

        if (StringUtils.isBlank(request.getUsername())){
            throw new GlobalException(ApiEnum.USERNAME_OR_PASSWORD_IS_NULL);
        }
        if (StringUtils.isBlank(request.getPassword())){
            throw new GlobalException(ApiEnum.USERNAME_OR_PASSWORD_IS_NULL);
        }
        if (StringUtils.isBlank(request.getVerificationCode())){
            throw new GlobalException(ApiEnum.USERNAME_OR_PASSWORD_IS_NULL);
        }

        User user = userService.login(request);
        if (user == null){
            throw new GlobalException(ApiEnum.USERNAME_OR_PASSWORD_IS_ERROR);
        }
        redisTemplate.opsForValue().set(user.getId()+"_user_login_token",user);

//        String token = UUID.randomUUID().toString().replaceAll("-","");
//        Cookie cookie = new Cookie("token",token);
//        cookie.setMaxAge(3600);
//        httpServletResponse.addCookie(cookie);
//        httpServletRequest.getSession().setAttribute(token,user);

        Map<String,Object> map = new HashMap<>();
        map.put("userId",user.getId());
        map.put("username",user.getUsername());
        map.put("role",user.getRole());
        String jwt = JwtUtils.createJWT(user.getId().toString(),map,user.getId().toString(),900l);

        Map<String,Object> result = Maps.newHashMap();
        result.put("user",user);
        result.put("token",jwt);
        return R.ok(result);
    }

}
